package com.anita.member.application.service;

import com.anita.member.application.port.in.MemberUpdateAvatarUseCase;
import com.anita.member.common.UploadResult;
import com.anita.member.common.enums.Resp;
import com.anita.member.common.exception.BusinessException;
import com.anita.member.domain.model.member.Avatar;
import com.anita.member.domain.model.member.Member;
import com.anita.member.domain.model.member.MemberId;
import com.anita.member.domain.repository.MemberRepository;
import com.anita.member.domain.service.ImageStorageService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Optional;

/**
 * @author qiu
 * @date 2025/10/22
 * @description
 */
@Slf4j
@Service
@Transactional
public class MemberUpdateAvatarService implements MemberUpdateAvatarUseCase {

    @Resource
    private MemberRepository memberRepository;

    @Resource
    private ImageStorageService imageStorageService;

    /**
     * 更新会员头像
     * @param id
     * @param file
     */
    @Override
    public String updateAvatar(Long id, MultipartFile file) {
        Optional<Member> memberOptional = memberRepository.findById(MemberId.of(id));

        if(memberOptional.isEmpty()){
            throw new BusinessException(Resp.USER_NOT_FOUND);
        }

        try{
            UploadResult uploadResult = imageStorageService.upload(file);

            //获取上传文件的url
            String url = uploadResult.getUrl();

            //更新会员头像
            Member member = memberOptional.get();
            member.updateAvatar(Avatar.of(url));

            //保存更新
            memberRepository.save(member);

            return uploadResult.getUrl();
        }catch (Exception e){
            log.error("上传头像失败: {}", e.getMessage());
            throw new BusinessException(Resp.UPLOAD_FILE_FAILED);
        }
    }
}
